package com.device.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author chengyadong
 * @date 2024/2/28 15:11
 * @description
 */
@Configuration
@EnableWebSecurity
public class DefaultSecurityConfig {

	/**
	 * Spring Security 过滤链配置（此处是纯Spring Security相关配置）
	 */
	@Bean
	@Order(2)
	public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
			throws Exception {
		http
				.authorizeHttpRequests(authorize ->
						authorize
								.requestMatchers("/assets/**", "/webjars/**").permitAll()
								.anyRequest().authenticated()
				)
				// UsernamePasswordAuthenticationFilter初始化
				.formLogin(Customizer.withDefaults());
		return http.build();
	}


	/**
	 * 模拟用户
	 *
	 * @return
	 */
	@Bean
	UserDetailsService users() {
		UserDetails user = User.builder()
				.username("admin")
				.password("1234567")
				.passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode)
				.roles("admin")
				.authorities("ROLE_admin")
				.build();
		return new InMemoryUserDetailsManager(user);
	}

}
